package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author Cx
 * @stage secondStageOfWeb
 * @creat 2020-11-10 10:24
 */
@RestController
public class AjaxController {

    private List<Map<String, Object>> dbList = new ArrayList<>();

    public AjaxController() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", "1");
        map.put("name", "手机类");
        map.put("parentId", null);
        map.put("remark", "2020新款式");
        map.put("createdTime", new Date());
        dbList.add(map);
    }

    @CrossOrigin /* 跨域 */
    @RequestMapping("/doAjaxStart")
    public String doAjaxGet01() {
        return "Response Result Of Ajax Get Request 01";
    }

    @RequestMapping("/doAjaxGet")
    public List<Map<String, Object>> doAjaxGet() {
        return dbList;
    }

    @RequestMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String, Object> map) {
        map.put("createdTime", new Date());
        dbList.add(map);
        return "save ok";
    }

    @RequestMapping("/doAjaxDelete")
    public String doAjaxDelete(String id) {
        //获取迭代器对象,然后迭代list集合,找到id对应的元素,进行删除操作
        Iterator it = dbList.iterator();
        while (it.hasNext()) {
            Map<String, Object> map = (Map<String, Object>) it.next();
            if (map.get("id").equals(id)) {
//                dbList.remove(map);
                it.remove();
            }
        }
        return "delete ok";
    }

    @RequestMapping("/doAjaxUpdate")
    public String doAjaxUpdate(@RequestParam Map<String, Object> updateMap) {
        Iterator it = dbList.iterator();
        while (it.hasNext()) {
            Map<String, Object> map = (Map<String, Object>) it.next();
            if (map.get("id").equals(updateMap.get("id"))) {
                map.put("name", updateMap.get("name"));
                map.put("remark", updateMap.get("remark"));
            }
        }
        return "update ok";
    }

}
